package cn.edu.tju.elm.repository;

import cn.edu.tju.elm.model.Cart;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.math.BigDecimal;
import java.util.List;

public interface CartRepository extends JpaRepository<Cart, Long> {
    @Query(
            value = """
        SELECT SUM(i.FOOD_PRICE * c.quantity) AS total_price
        FROM cart c
        JOIN food i ON c.food_id = i.id
        WHERE c.customer_id = :userId AND c.business_id = :businessId AND c.deleted = false
        """,
            nativeQuery = true  // 关键：标记为原生 SQL
    )
    BigDecimal getCartTotalByUserAndBusiness(Long userId, Long businessId);


    /**
     * 根据用户ID和店铺ID查询购物车项
     */
    List<Cart> findByCustomerIdAndBusinessId(Long customerId, Long businessId);
    List<Cart> findByCustomerId(Long customerId);


    // 根据用户ID查询购物车项


    // 根据用户ID和店铺ID查询购物车项





    // 根据用户ID、商家ID和商品ID查找现有购物车项
    @Query("SELECT c FROM Cart c WHERE c.customer.id = :customerId AND c.business.id = :businessId AND c.food.id = :foodId")
    Cart findByCustomerIdAndBusinessIdAndFoodId(@Param("customerId") Long customerId,
                                                @Param("businessId") Long businessId,
                                                @Param("foodId") Long foodId);



    // 根据用户和商家删除购物车项（用于订单创建后清空购物车）
    @Modifying
    @Query("DELETE FROM Cart c WHERE c.customer.id = :userId AND c.business.id = :businessId")
    void deleteByCustomerIdAndBusinessId(@Param("userId") Long userId, @Param("businessId") Long businessId);

    @Query("SELECT c FROM Cart c JOIN FETCH c.food f JOIN FETCH f.business b " +
            "WHERE c.customer.id = :customerId AND b.id = :businessId")
    List<Cart> findByCustomerIdAndBusinessIdWithFood(
            @Param("customerId") Long customerId,
            @Param("businessId") Long businessId);

    // 全量查询也要确保关联正确
    @Query("SELECT c FROM Cart c JOIN FETCH c.food f WHERE c.customer.id = :customerId")
    List<Cart> findByCustomerIdWithFood(@Param("customerId") Long customerId);


}
